package com.tao.YanMoDesignPattern.composite.pattern;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Mi_Tao
 * @Date 2023/8/27
 * @Description
 * @Version 1.0
 **/
public class Composite extends Component{

    // 用来存储组合对象中包含的子组件
    private List<Component> childComponents = null;
    @Override
    public void someOperation() {
        if (childComponents != null){
            // 递归 遍历子组件
            childComponents.forEach(c->c.someOperation());
        }
    }

    public void addChild(Component child){
        // 延迟初始化
        if (childComponents == null){
            childComponents = new ArrayList<>();
        }
        childComponents.add(child);
    }

    @Override
    public void removeChild(Component c) {
        if (childComponents!= null){
            childComponents.remove(c);
        }
    }

    public Component getChildren(int index){
        if (childComponents != null && index > 0 &&index < childComponents.size()){
            return childComponents.get(index);
        }
        return null;
    }

}
